//
// Created by 33145 on 2023/5/27.
//

#include "util.h"
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <cstring>
#include <arpa/inet.h>
#include <string>
#include <fcntl.h>
#include "log.h"


namespace rocket {

  static int g_pid = 0;

  static thread_local int t_thread_id = 0;

  pid_t getPid() {
    if (g_pid != 0) {
      return g_pid;
    }
    return getpid();
  }

  pid_t getThreadId() {
    if (t_thread_id != 0) {
      return t_thread_id;
    }
    return syscall(SYS_gettid);
  }


  int64_t getNowMs() {
    timeval val;
    gettimeofday(&val, NULL);

    return val.tv_sec * 1000 + val.tv_usec / 1000;

  }


  int32_t getInt32FromNetByte(const char* buf) {
    int32_t re;
    memcpy(&re, buf, sizeof(re));
    return ntohl(re);
  }

  static int g_msg_id_length = 20;
  static int g_random_fd = -1;
  static thread_local std::string t_msg_id_no;
  static thread_local std::string t_max_msg_id_no;

  // 获取随机的数字的字符序列
  std::string MsgIDUtil::GenMsgID() {
    if (t_msg_id_no.empty() || t_msg_id_no == t_max_msg_id_no) {
      if (g_random_fd == -1) {
        // 打开一个随机文件，fd会获得随机文件的句柄
        g_random_fd = open("/dev/urandom", O_RDONLY);
      }
      std::string res(g_msg_id_length, 0);
      if (read(g_random_fd, &res[0], g_msg_id_length) != g_msg_id_length) {
        LOG_ERROR("read from /dev/urandom error");
        return "";
      }
      for (auto &ch : res) {
        uint8_t x = ((uint8_t)ch) % 10l;
        ch = x + '0';
        t_max_msg_id_no += '9';
      }
      t_msg_id_no = res;
    } else {
      int i = t_msg_id_no.size() - 1;
      while(t_msg_id_no[i] == '9' && i >= 0) {
        i--;
      }
      if (i >= 0) {
        t_msg_id_no[i] += 1;
        for (size_t j = i + 1; j < t_msg_id_no.size(); j++) {
          t_msg_id_no[j] = '0';
        }
      }
    }
    return t_msg_id_no;
  }
}